<template>
  <div class="statistics">
    <h1 class="page-title">数据统计</h1>

    <!-- 概览卡片 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="6">
        <el-card class="overview-card" shadow="hover">
          <div class="card-content">
            <div class="icon-wrapper" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <el-icon :size="40"><User /></el-icon>
            </div>
            <div class="info">
              <div class="label">总用户数</div>
              <div class="value">{{ platformStats.totalUsers || 0 }}</div>
              <div class="trend">
                <span class="trend-text">较上月</span>
                <span class="trend-value" :class="{ 'trend-up': true }">
                  +{{ platformStats.userGrowth || 0 }}%
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="overview-card" shadow="hover">
          <div class="card-content">
            <div class="icon-wrapper" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
              <el-icon :size="40"><UserFilled /></el-icon>
            </div>
            <div class="info">
              <div class="label">俱乐部数</div>
              <div class="value">{{ platformStats.totalClubs || 0 }}</div>
              <div class="trend">
                <span class="trend-text">活跃</span>
                <span class="trend-value">{{ platformStats.activeClubs || 0 }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="overview-card" shadow="hover">
          <div class="card-content">
            <div class="icon-wrapper" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
              <el-icon :size="40"><Calendar /></el-icon>
            </div>
            <div class="info">
              <div class="label">总活动数</div>
              <div class="value">{{ platformStats.totalEvents || 0 }}</div>
              <div class="trend">
                <span class="trend-text">进行中</span>
                <span class="trend-value">{{ platformStats.ongoingEvents || 0 }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="overview-card" shadow="hover">
          <div class="card-content">
            <div class="icon-wrapper" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
              <el-icon :size="40"><Location /></el-icon>
            </div>
            <div class="info">
              <div class="label">场地数量</div>
              <div class="value">{{ platformStats.totalVenues || 0 }}</div>
              <div class="trend">
                <span class="trend-text">可用</span>
                <span class="trend-value">{{ platformStats.availableVenues || 0 }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 用户增长趋势 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span class="card-title">用户增长趋势</span>
              <el-radio-group v-model="userChartPeriod" size="small" @change="loadUserStats">
                <el-radio-button label="7">最近7天</el-radio-button>
                <el-radio-button label="30">最近30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="userChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 活动统计 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span class="card-title">活动状态分布</span>
          </template>
          <div ref="eventChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <!-- 运动类型热度 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span class="card-title">运动类型热度</span>
          </template>
          <div ref="sportChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 城市活动分布 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span class="card-title">城市活动分布（TOP 10）</span>
          </template>
          <div ref="cityChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 排行榜 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 俱乐部排行 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span class="card-title">俱乐部排行榜</span>
              <el-select v-model="clubRankType" size="small" style="width: 120px" @change="loadClubRankings">
                <el-option label="活跃度" value="activity" />
                <el-option label="成员数" value="members" />
              </el-select>
            </div>
          </template>
          <el-table :data="clubRankings" stripe style="width: 100%">
            <el-table-column type="index" label="排名" width="80" />
            <el-table-column prop="name" label="俱乐部名称" />
            <el-table-column prop="value" label="数值" width="120" align="right">
              <template #default="{ row }">
                <el-tag>{{ row.value }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 用户排行 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span class="card-title">用户排行榜</span>
              <el-select v-model="userRankType" size="small" style="width: 120px" @change="loadUserRankings">
                <el-option label="积分" value="points" />
                <el-option label="活跃度" value="activity" />
              </el-select>
            </div>
          </template>
          <el-table :data="userRankings" stripe style="width: 100%">
            <el-table-column type="index" label="排名" width="80" />
            <el-table-column prop="name" label="用户昵称" />
            <el-table-column prop="value" label="数值" width="120" align="right">
              <template #default="{ row }">
                <el-tag type="success">{{ row.value }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { adminApi } from '@/api/admin'
import * as echarts from 'echarts'

// 数据
const platformStats = ref({})
const userChartPeriod = ref('30')
const clubRankType = ref('activity')
const userRankType = ref('points')
const clubRankings = ref([])
const userRankings = ref([])

// 图表实例
const userChartRef = ref(null)
const eventChartRef = ref(null)
const sportChartRef = ref(null)
const cityChartRef = ref(null)
let userChart = null
let eventChart = null
let sportChart = null
let cityChart = null

onMounted(() => {
  loadAllData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  disposeCharts()
})

const loadAllData = async () => {
  await loadPlatformStats()
  await nextTick()
  initCharts()
  loadUserStats()
  loadEventStats()
  loadSportStats()
  loadCityStats()
  loadClubRankings()
  loadUserRankings()
}

const loadPlatformStats = async () => {
  try {
    const data = await adminApi.getDashboard()
    platformStats.value = data || {}
  } catch (error) {
    console.error('加载平台统计失败:', error)
  }
}

const initCharts = () => {
  if (userChartRef.value) userChart = echarts.init(userChartRef.value)
  if (eventChartRef.value) eventChart = echarts.init(eventChartRef.value)
  if (sportChartRef.value) sportChart = echarts.init(sportChartRef.value)
  if (cityChartRef.value) cityChart = echarts.init(cityChartRef.value)
}

const loadUserStats = async () => {
  try {
    const days = parseInt(userChartPeriod.value)
    const data = await adminApi.getUserActivityStatistics(days)
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' }
      },
      legend: {
        data: ['新增用户', '活跃用户']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: data.dates || generateMockDates(days)
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '新增用户',
          type: 'line',
          stack: 'Total',
          smooth: true,
          lineStyle: { width: 2 },
          areaStyle: { opacity: 0.3 },
          emphasis: { focus: 'series' },
          data: data.newUsers || generateMockData(days, 5, 50)
        },
        {
          name: '活跃用户',
          type: 'line',
          stack: 'Total',
          smooth: true,
          lineStyle: { width: 2 },
          areaStyle: { opacity: 0.3 },
          emphasis: { focus: 'series' },
          data: data.activeUsers || generateMockData(days, 10, 100)
        }
      ]
    }
    
    userChart?.setOption(option)
  } catch (error) {
    console.error('加载用户统计失败:', error)
  }
}

const loadEventStats = async () => {
  try {
    const data = await adminApi.getEventStatistics({ days: 30 })
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '活动状态',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c}'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          data: data.statusDistribution || [
            { value: 45, name: '待开始' },
            { value: 30, name: '进行中' },
            { value: 20, name: '已结束' },
            { value: 5, name: '已取消' }
          ]
        }
      ]
    }
    
    eventChart?.setOption(option)
  } catch (error) {
    console.error('加载活动统计失败:', error)
  }
}

const loadSportStats = async () => {
  try {
    const data = await adminApi.getSportTypePopularity(30)
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01]
      },
      yAxis: {
        type: 'category',
        data: data.types || ['足球', '篮球', '羽毛球', '网球', '游泳', '健身']
      },
      series: [
        {
          type: 'bar',
          data: data.values || [320, 280, 240, 180, 150, 120],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#667eea' },
              { offset: 1, color: '#764ba2' }
            ])
          }
        }
      ]
    }
    
    sportChart?.setOption(option)
  } catch (error) {
    console.error('加载运动类型统计失败:', error)
  }
}

const loadCityStats = async () => {
  try {
    const data = await adminApi.getCityDistribution(30)
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.cities || ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安', '南京', '苏州']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          type: 'bar',
          data: data.counts || [320, 280, 240, 200, 180, 160, 140, 120, 100, 80],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              { offset: 0, color: '#4facfe' },
              { offset: 1, color: '#00f2fe' }
            ])
          }
        }
      ]
    }
    
    cityChart?.setOption(option)
  } catch (error) {
    console.error('加载城市统计失败:', error)
  }
}

const loadClubRankings = async () => {
  try {
    const data = await adminApi.getClubRankings(clubRankType.value, 10)
    clubRankings.value = data.rankings || generateMockRankings('俱乐部', 10)
  } catch (error) {
    console.error('加载俱乐部排行失败:', error)
    clubRankings.value = generateMockRankings('俱乐部', 10)
  }
}

const loadUserRankings = async () => {
  try {
    const data = await adminApi.getUserRankings(userRankType.value, 10)
    userRankings.value = data.rankings || generateMockRankings('用户', 10)
  } catch (error) {
    console.error('加载用户排行失败:', error)
    userRankings.value = generateMockRankings('用户', 10)
  }
}

const handleResize = () => {
  userChart?.resize()
  eventChart?.resize()
  sportChart?.resize()
  cityChart?.resize()
}

const disposeCharts = () => {
  userChart?.dispose()
  eventChart?.dispose()
  sportChart?.dispose()
  cityChart?.dispose()
}

// Mock数据生成函数
const generateMockDates = (days) => {
  const dates = []
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    dates.push(`${date.getMonth() + 1}/${date.getDate()}`)
  }
  return dates
}

const generateMockData = (length, min, max) => {
  return Array.from({ length }, () => Math.floor(Math.random() * (max - min + 1)) + min)
}

const generateMockRankings = (prefix, count) => {
  return Array.from({ length: count }, (_, i) => ({
    name: `${prefix}${i + 1}`,
    value: Math.floor(Math.random() * 1000) + 100
  }))
}
</script>

<style scoped>
.statistics {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #303133;
}

.overview-row {
  margin-bottom: 20px;
}

.overview-card {
  border-radius: 8px;
}

.card-content {
  display: flex;
  gap: 16px;
  align-items: center;
}

.icon-wrapper {
  width: 70px;
  height: 70px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.info {
  flex: 1;
}

.label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.trend {
  font-size: 12px;
}

.trend-text {
  color: #909399;
  margin-right: 8px;
}

.trend-value {
  color: #67c23a;
  font-weight: 600;
}

.trend-up {
  color: #67c23a;
}

.charts-row {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: 600;
  font-size: 16px;
}

.chart-container {
  width: 100%;
  height: 350px;
}
</style>

